// pages/video/video.js
let app = getApp();

Page({
	/**
	 * 页面的初始数据
	 */
	data: {
		//当textarea获取焦点时自适应高度，失去焦点时不自适应高度
		//自适应高度时，style中的height无效
		auto_height: true,
		num: 1,
		selectPaymentType: 1, // 选择的支付类型，1微信支付，2余额支付
		discRollup: false, //优惠卷弹窗
		couponIcon:
			'https://miaommeis-1301812909.cos.ap-guangzhou.myqcloud.com/mall/%E5%9B%BE%E6%A0%87%EF%BC%8F%E8%B4%AD%E7%89%A9%E5%88%B8%402x.png', //优惠卷图标
		chooseShoppingVchr: 1, //选择购物券,0是不使用,1使用
		chooseShopping: 1,
		video_id: '',
		goodImg: '', // 商品图片
		adders: '', // 地址
		lives: '', // 直播商品跳转过来的
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function (options) {
		wx.showLoading({
			title: '加载中',
		});
		let that = this;
		let attrs = JSON.parse(options.attrs);
		that.setData({
			attrs: attrs,
			productId: options.id,
			price_share: options.price_share,
			name: options.name,
			video_id: options.videoid,
			activ: options.activ,
			puid: app.store.getState().uid,
			activity_id: app.store.getState().activity_id,
			lives: options.lives ? options.lives : '',
		});
		setTimeout(() => {
			that.setData({
				num: options.stepper,
			});
		}, 1000);
		that.get_mall_payData(options.id, options.stepper, attrs.id);
	},

	// 获取商品信息
	get_mall_payData(id, num, attr) {
		let that = this;
		let data = {};
		data = {
			id: id,
			num: num,
			attr_id: attr,
			lives: that.data.lives ? that.data.lives : '',
		};
		app.http({
			url: app.api.get_mall_payData,
			data: data,
			//method: 'get',
		})
			.then((res) => {
				let price;

				// 自购省
				let purchase_money = res.data.data.purchase_money ? res.data.data.purchase_money * Number(num) : 0;
				let wallet = res.data.data.wallet; // 购物券余额
				console.log('wallet---购物余额---',wallet)

				if (res.data.data.wallet_money) { // 如果有购物卷抵扣金额
					// 支付价格 = 商品单价 * 数量 + 运费 - 购物卷 * 数量 - 自购省 * 数量
					price =
						Number(that.data.attrs.price) * Number(num) +
						Number(res.data.data.freight) -
						Number(res.data.data.wallet_money) *  Number(num) -
						Number(purchase_money) * Number(num);
					console.log('支付价格 price---',price);
					console.log('总的自购省',Number(purchase_money) * Number(num));

					// if (wallet >= priceOne){
					// 	price = wallet - priceOne
					// } else {
					// 	price = priceOne - wallet
					// }
				} else {
					// 支付价格 = 数量 * 价格 + 运费 - 自购省 * 数量
					price =
						Number(that.data.attrs.price) * Number(num) +
						Number(res.data.data.freight) -
						Number(purchase_money) * Number(num);
				}

				that.setData({
					payData: res.data.data,
					adders: res.data.data.adders,
					wallet: res.data.data.wallet,
					wallet_money: res.data.data.wallet_money * Number(num) ,
					t: res.data.data.wallet_money,
					// price: price.toFixed(2),
					price: parseFloat(price).toFixed(2),

					goodImg: res.data.data.attr.img,
					purchase_money: parseFloat(purchase_money).toFixed(2),
				});
				wx.hideLoading();
			})
			.catch((err) => {});
	},
	// 计算价格
	calcThePrc() {
		let that = this;
		let a = that.data.attrs.price; //单价
		let b = that.data.payData.freight ? that.data.payData.freight : 0; //运费
		let c = that.data.payData.wallet_money - 0; //优惠卷余额
		let f = that.data.wallet_money - 0; //优惠卷余额
		let t = that.data.t - 0; //优惠卷余额
		let d = that.data.wallet - 0; //优惠卷
		let num = that.data.num || 1;
		let e =
			that.data.payData.purchase_money - 0
				? that.data.payData.purchase_money - 0
				: 0; //自购省

		let price;
		// 判断有没有优惠卷和是否使用优惠卷
		if (c && that.data.chooseShopping == 1) {
			// 判断优惠卷是否超过上限
			if (Number(t).toFixed(2) * Number(num) >= d) {
				price =
					Number(t).toFixed(2) * Number(num) -
					Number(d).toFixed(2) -
					Number(e).toFixed(2) * Number(num) -
					Number(b).toFixed(2);
				that.setData({
					price: price.toFixed(2), //数量 * 单价 + 运费 - 数量 *优惠卷 - (数量 * 自购省)
					num: num, //数量
					wallet_money: Number(d).toFixed(2), //优惠卷余额
					purchase_money: (Number(num) * Number(e)).toFixed(2),
				});
			} else {
				price =
					Number(t).toFixed(2) * Number(num) -
					Number(d).toFixed(2) -
					Number(e).toFixed(2) * Number(num) -
					Number(b).toFixed(2);
				console.log(num * Number(t));
				that.setData({
					price: price.toFixed(2), //数量 * 单价 + 运费 - 数量 *优惠卷 - (数量 * 自购省)
					num: num, //数量
					wallet_money: (Number(num) * Number(t)).toFixed(2), //优惠卷余额
					purchase_money: (Number(num) * Number(e)).toFixed(2),
				});
			}
		} else {
			price =
				(Number(num) * Number(a)).toFixed(2) -
				(Number(num) * Number(e)).toFixed(2) -
				Number(b);
			that.setData({
				price: price.toFixed(2), //数量 * 单价 + 运费 - (数量 * 自购省)
				num: num, //数量
				purchase_money: (Number(num) * Number(e)).toFixed(2),
			});
		}
	},

	// 优惠卷弹窗
	onClose() {
		let that = this;
		that.setData({
			discRollup: !that.data.discRollup,
		});
	},
	// 选择优惠卷
	chooseShoppingVchr(e) {
		let index = e.currentTarget.dataset.index;
		this.setData({
			chooseShoppingVchr: index,
		});
	},
	// 是否使用优惠卷
	carryOut() {
		let that = this;
		that.setData({
			chooseShopping: that.data.chooseShoppingVchr,
			discRollup: !that.data.discRollup,
		});
		that.calcThePrc();
	},


	// 确认使用余额支付
	payt() {
		let that = this;
		wx.showModal({
			title: '提示',
			content: '确认使用余额支付',
			success(res) {
				if (res.confirm) {
					//console.log('用户点击确定')
					that.pay();
				} else if (res.cancel) {
					//console.log('用户点击取消') } }
				}
			},
		});
	},
	// 支付
	pay() {
		if (!this.data.adders) {
			wx.showToast({
				title: '请选择收货地址',
				icon: 'none',
				duration: 2000,
			});
			return;
		}

		let that = this,
			productId = that.data.productId, //商品id
			num = that.data.num, //数量
			selectPaymentType = that.data.selectPaymentType, //支付方式
			attr_id = that.data.payData.attr.id, //商品规格id
			chooseShopping = that.data.chooseShopping, //是否使用优惠卷
			adders_id = that.data.adders ? that.data.adders.id : '', //地址id
			desc = that.data.orderNotesTextareaValue || '', //订单备注
			activity_log_id = that.data.activ || '', //活动拼团列表id
			video_id = that.data.video_id, //视频id
			puid = that.data.puid || '', //分享id
			lives = that.data.lives || ''; //直播商品跳转

		let data = {
			id: productId, // 商品id
			num: num, // 购买数量
			pay_type: selectPaymentType, // 支付类型  1  微信 ，  2  余额
			attr_id: attr_id, // 商品规格id
			wallet: chooseShopping, // 表示使用购物券  不适用不填写即可
			adders_id: adders_id, // 用户当前所选的支付地址 id 支付详情可以拿取到
			desc: desc, // 用户所输入的订单备注信息
		};
		//判断支付类型
		//活动拼团
		if (activity_log_id || video_id) {
			// 支付页面  请求参数  类型  3 - 活动商品 -入团
			data.activity_log_id = activity_log_id;
			data.video_id = video_id;
			//活动商品
		} else if (that.data.activity_id) {
			// 支付页面 请求参数 类型   4  - 视频分享常规商品
			data.activity_log_id = that.data.activity_id;
			data.puid = puid;
			// /分享者
		} else if (video_id) {
			// 支付页面 请求参数 类型   4  - 视频分享常规商品
			data.video_id = video_id;
			// /分享者
		} else if (puid) {
			// 支付页面 请求参数 类型   5  - 用户分享常规商品
			data.puid = puid;
			data.activity_log_id = that.data.activity_id;
		} else if (lives) {
			//直播商品跳转
			data.lives = lives;
		} else {
			// 常规商品;
			// 支付页面  请求参数 类型1  - 常规商品 直接购买
			data = data;
		}
		wx.showToast({
			title: '加载中...',
			icon: 'loading',
			mask: true,
		});
		app.http({
			url: app.api.get_mall_indexPay,
			data: data,
			//method: 'get',
		})
			.then((res) => {
				var orderId = res.data.data.orderid;
				let log_id = res.data.data.log_id;
				// 如果是微信支付
				if (res.data.data && orderId && res.data.data.pay_type == 1) {
					var data = res.data.data;
					wx.requestPayment({
						//调起支付
						//下边参数具体看微信小程序官方文档
						timeStamp: data.timeStamp,
						nonceStr: data.nonceStr,
						package: data.package,
						signType: data.signType,
						paySign: data.paySign,
						success(res) {
							// 微信支付ok 直接跳转到我的订单列表
							if (res.errMsg == 'requestPayment:ok') {
								wx.showToast({
									title: '支付成功!',
									icon: 'success',
									duration: 2000,
								});
								app.store.setState({
									uid: '',
								});
								that.setData({
									puid: '',
								});
								wx.requestSubscribeMessage({
									tmplIds: [
										'FddT6-1bVu2lfiggUR7FVmS0mwrvTlGIgksy6xh94XE',
									],
									success(res) {},
								});
								if (that.data.payData.is_activity == 1) {
									setTimeout(() => {
										wx.redirectTo({
											url: `/pages/successfullyOpened/successfullyOpened?id=${log_id}`,
										});
									}, 2000);
								} else {
									setTimeout(() => {
										wx.redirectTo({
											url: `/pages/order/orderManage/orderManage?index=0`,
										});
									}, 2000);
								}
							}
						},
						fail(res) {},
					});
					// 如果是余额支付
				} else {
					wx.showToast({
						title: '支付成功!',
						icon: 'success',
						duration: 2000,
					});
					app.store.setState({
						uid: '',
					});
					that.setData({
						puid: '',
					});
					wx.requestSubscribeMessage({
						tmplIds: [
							'FddT6-1bVu2lfiggUR7FVmS0mwrvTlGIgksy6xh94XE',
						],
						success(res) {},
					});
					if (that.data.payData.is_activity == 1) {
						setTimeout(() => {
							wx.redirectTo({
								url: `/pages/successfullyOpened/successfullyOpened?id=${log_id}`,
							});
						}, 2000);
					} else {
						setTimeout(() => {
							wx.redirectTo({
								url: `/pages/order/orderManage/orderManage?index=0`,
							});
						}, 2000);
					}
				}
			})
			.catch((err) => {
				// wx.showToast({
				// 	title: err.data.msg || '麻烦重新尝试',
				// 	icon: 'waiting',
				// 	duration: 1500,
				// });
			});
	},

	// 选择支付方式
	selectPaymentTypeFun(e) {
		let index = e.currentTarget.dataset.index;
		this.setData({
			selectPaymentType: index,
		});
	},
	// 选择数量
	onChange(event) {
		let that = this;
		let num; //数量
		if (event) {
			num = event.detail; //数量
		} else {
			num = 1; //数量
		}
		that.setData({
			num: num, //数量
		});
		that.calcThePrc();
	},
	// 选择收货地址
	address() {
		let that = this;
		let index = 0;
		wx.navigateTo({
			url: `/pages/address/addressList/addressList?id=${index}`,
		});
	},

	// 订单备注键盘输入时事件
	commentbindinput(e) {
		this.setData({
			orderNotesTextareaValue: e.detail.value,
		});
	},
	// 订单备注输入框方法
	areablur: function () {
		this.setData({
			auto_height: false,
		});
	},
	areafocus: function () {
		this.setData({
			auto_height: true,
		});
	},
	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function () {
		let that = this;
		app.store.setState({
			uid: '',
		});
		that.setData({
			puid: '',
		});
	},
});
